// loading开关
export const loading_on_off = (e: any) => {
  e = !e
  return e
}

// ElMessage提示
import { ElMessage } from 'element-plus'
export const onElMessage = (data: any, title: any = '提交成功', type: any = false): any => {
  if (data.result == 0) {
    if (type === true) {
      ElMessage({
        message: title,
        type: 'success'
      })
    }
    return true
  } else {
    if (type === true) {
      ElMessage({
        message: data.error_msg,
        type: 'error'
      })
    }
    return false
  }
}

// mock 动态页数
export const data_num = (pageSize: any, pageNum: any, total: any) => {
  return pageNum < Math.ceil(total / pageSize) ? pageSize : total - (pageNum - 1) * pageSize
}

// 数据过滤：去除空数据
export const filterFales = (e: any) => {
  const obj = JSON.parse(JSON.stringify(e))
  for (const key in obj) {
    if (obj[key] === '' || obj[key] === null || obj[key] === undefined) {
      delete obj[key]
    }
  }
  return obj
}

// 数据处理：生成A-Z
export const generateAlphabet = (): any => {
  const alphabet = []
  const startChar = 'A' // 开始字符
  const endChar = 'Z' // 结束字符
  for (let i = startChar.charCodeAt(0); i <= endChar.charCodeAt(0); i++) {
    alphabet.push(String.fromCharCode(i))
  }

  return alphabet
}

// 数据处理：部门列表处理
export const transformData = (data: any, parentId: any = 1): any => {
  const result: any = []
  for (let i = 0; i < data.length; i++) {
    if (data[i].parentId === parentId) {
      const node: any = {
        value: data[i].id,
        label: data[i].departName
      }
      const children: any = transformData(data, data[i].id)
      if (children.length > 0) {
        node.children = children
      }
      result.push(node)
    }
  }
  return result
}

// 下载excel
export const downloadExcel = (file: any, title: any, type: any): any => {
  // if (file.result && file.result != 0) {
  //   ElMessage.error(res.error_msg || "下载失败!");
  //   return false;
  // }
  const link = document.createElement('a')
  link.style.display = 'none'
  //设置连接
  link.href = URL.createObjectURL(
    new Blob([file], {
      type: type || 'application/vnd.ms-excel'
    })
  )
  link.download = `${title}`
  document.body.appendChild(link)
  //模拟点击事件
  link.click()
  document.body.removeChild(link)
}

// 校验手机号
export const validatePhoneNumber = (phoneNumber: any): any => {
  // 使用正则表达式匹配手机号的格式
  const regex: any = /^(?:(?:\+|00)86)?1[3-9]\d{9}$/

  // 校验手机号格式
  if (regex.test(phoneNumber)) {
    return true
  } else {
    ElMessage({
      message: '请确认手机号是否正确',
      type: 'error'
    })
    return false
  }
}

// import store from '@/store'
// // 网络图片转File
// export const urlToFile = async (url: any) => {
//   const headers: any = new Headers()
//   headers.append('authorization', store.state.User.userinfo.token)

//   fetch(url, { headers: headers })
//     .then((res) => {
//       console.log(res.json())
//     })
//     .catch((error) => {
//       console.log(error)
//     })
// }

// 深拷贝
export const deepCopy = (obj: any): any => {
  if (typeof obj !== 'object' || obj === null) {
    return obj
  }
  let result: any
  if (Array.isArray(obj)) {
    result = []
    for (let i = 0; i < obj.length; i++) {
      result.push(deepCopy(obj[i]))
    }
  } else {
    result = {}
    for (const key in obj) {
      if (Object.prototype.hasOwnProperty.call(obj, key)) {
        result[key] = deepCopy(obj[key])
      }
    }
  }
  return result
}

// 数字转文字读法
export const convertToChineseNumber = (number: any): any => {
  const chineseNumbers: any = {
    0: '零',
    1: '一',
    2: '二',
    3: '三',
    4: '四',
    5: '五',
    6: '六',
    7: '七',
    8: '八',
    9: '九'
  }
  const chineseUnits: any = ['', '十', '百', '千', '万']

  const digits: any = String(number).split('')
  const chineseDigits: any = []
  for (let i = 0; i < digits.length; i++) {
    const digit: any = digits[i]
    const unit: any = chineseUnits[digits.length - i - 1]
    if (digit !== '0') {
      chineseDigits.push(chineseNumbers[digit] + unit)
    } else if (chineseDigits[chineseDigits.length - 1] !== '零') {
      chineseDigits.push('零')
    }
  }
  return chineseDigits.join('')
}

// 节流函数
export const throttle = (func: any): any => {
  let timer: any = null
  return function (this: any, ...args: any): any {
    if (timer === null) {
      func.apply(this, args)
      timer = setTimeout(() => {
        timer = null
      }, 1000)
    }
  }
}

// import { REPLACE_PREFIX } from '@/service/request/config'
// // 替换图片前缀 - http
// export const alternatePrefix = (data) => {
//   return JSON.parse(JSON.stringify(data).replaceAll('((FileURL))', `${REPLACE_PREFIX}`))
// }
// // 替换图片前缀 - 特殊字符
// export const revivificationPrefix = (data) => {
//   return JSON.parse(JSON.stringify(data).replaceAll(`${REPLACE_PREFIX}`, '((FileURL))'))
// }

// FormData 获取大小
export const getFormDataSizeInBytes = (formData: any): any => {
  let size: any = 0
  for (const [key, value] of formData.entries()) {
    key
    if (value instanceof File) {
      // 如果是文件，则直接累加文件大小
      size += value.size
    } else {
      // 对于非文件数据，转换为字符串并计算UTF-8编码后的字节长度
      const valueString = String(value)
      size += new TextEncoder().encode(valueString).length
    }
  }
  return size
}

// 颜色算法
/**
 *
 * @param startColor 开始颜色
 * @param endColor 结束颜色
 * @param steps 步长
 * @returns
 */
export const interpolateGradientColors = (startColor: string, endColor: string, steps: number) => {
  // 解析起始和结束颜色的RGBA分量
  const startRGBA = startColor.match(/\d+(\.\d+)?/g)!.map(Number)
  const endRGBA = endColor.match(/\d+(\.\d+)?/g)!.map(Number)

  // 创建颜色数组来存储中间颜色
  const colors = []

  // 计算每一步的颜色变化量
  const colorDeltas = endRGBA.map((end, i) => (end - startRGBA[i]) / steps)

  // 计算每一步的中间颜色
  for (let step = 0; step <= steps; step++) {
    // 计算当前步的RGBA分量
    const currentRGBA = startRGBA.map((start, i) => {
      // 对于透明度，我们不进行四舍五入，而是保留其小数精度
      if (i === 3) {
        // 假设最后一个分量是透明度（alpha）
        return (start + colorDeltas[i] * step).toFixed(2)
      } else {
        return Math.round(start + colorDeltas[i] * step)
      }
    })

    // 格式化当前步的颜色为rgba字符串
    const currentColor = `rgba(${currentRGBA.join(', ')})`

    // 将当前颜色添加到颜色数组中
    colors.push(currentColor)
  }

  // 返回所有中间颜色的数组
  return colors
}
